//
//  WithDrawJiLuViewController.m
//  DA_V
//
//  Created by 周季阳 on 15/5/11.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "WithDrawJiLuViewController.h"
#import "InterFace.h"
#import "UIViewAdditions.h"
#import "WithdrawView.h"
#import "WithdrawLTableViewCell.h"
#import "PMCalendar.h"
#import "YoungAllData.h"

#import "UIScrollView+FCXRefresh.h"
#import "FCXRefreshFooterView.h"
#import "FCXRefreshHeaderView.h"
#import "GMDCircleLoader.h"
@interface WithDrawJiLuViewController ()<UITableViewDataSource,UITableViewDelegate,PMCalendarControllerDelegate,YoungDelegate>
{
    WithdrawView *withdrawView;
    UITableView *zTableView;
    NSInteger pageWithNotDeliver;//页数
    FCXRefreshFooterView *footerView;
}
@property(nonatomic,retain)PMCalendarController *pmCC;
@property (nonatomic, retain) UIButton *dateBtn;
@property(nonatomic, retain)NSString *dateNow;
@property(nonatomic,retain)NSMutableArray *zArrayData;
@property(nonatomic,retain)YoungAllData *data;
@end

@implementation WithDrawJiLuViewController
@synthesize pmCC,dateBtn,dateNow,zArrayData;

#pragma mark - ViewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    [self initNav];
    navTitle.text = @"提现记录";
    //隐藏信封
    navRightBtn.hidden = YES;
    //获取现在的日期
    [self strtime];
    pageWithNotDeliver = 1;
    self.data  = [[YoungAllData alloc]init];
    _data.delegate = self;
    [_data gainWithdrawRecord:[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] andPageID:[NSString stringWithFormat:@"%ld",(long)pageWithNotDeliver] andPerPage:@"15" andStartTime:@"" andEndTime:@""];
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中..." animated:YES];
    withdrawView = [[WithdrawView alloc] initWithFrame:CGRectMake(10, navView.bottom+20, SCREEN_WIDTH-20, 40)];
    withdrawView.backgroundColor = [UIColor whiteColor];
    withdrawView.zDate.text = @"日期";
    withdrawView.zDate.font = [UIFont systemFontOfSize:14];
    withdrawView.zTime.text = @"时间";
    withdrawView.zTime.font = [UIFont systemFontOfSize:14];
    withdrawView.zPrice.text = @"金额";
    withdrawView.zPrice.font = [UIFont systemFontOfSize:14];
    withdrawView.zState.text = @"状态";
    withdrawView.zState.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:withdrawView];
    
    
    dateBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
    if (SCREEN_WIDTH == 320) {
        dateBtn.frame = CGRectMake(SCREEN_WIDTH-80,29.5, 70,25);
    }else if (SCREEN_WIDTH == 375){
        dateBtn.frame = CGRectMake(SCREEN_WIDTH-80,35, 70,25);
    }else{
        dateBtn.frame = CGRectMake(SCREEN_WIDTH-80,48.9, 70,25);
    }
    dateBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    dateBtn.layer.borderWidth = 0.5;
    //[self.dateBtn setBackgroundImage:[UIImage imageNamed:@"applySelect"] forState:UIControlStateNormal];
    [dateBtn setTintColor:[UIColor whiteColor]];
    [dateBtn setTitle:dateNow forState:UIControlStateNormal];
    [dateBtn addTarget:self action:@selector(dateBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:dateBtn];
    zArrayData = [[NSMutableArray alloc]init];
    [self initUItableView];

    
}
#pragma mark - 获取提现记录回调
-(void)withdrawRecord:(NSDictionary *)sign{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    if ([[sign objectForKey:@"status"] isEqualToString:@"success"]) {
        [zArrayData removeAllObjects];
    [zArrayData addObjectsFromArray:[sign objectForKey:@"data"]];
        [zTableView reloadData];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[sign objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark － 上拉加载回调
-(void)shanglaRecord:(NSDictionary *)sign{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    if ([[sign objectForKey:@"status"] isEqualToString:@"success"]) {
        [zArrayData removeAllObjects];
        [zArrayData addObjectsFromArray:[sign objectForKey:@"data"]];
        [zTableView reloadData];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[sign objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - 提现记录回调失败
-(void)requistFail{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
#pragma mark - initUItableView
-(void)initUItableView{
    if (SCREEN_HEIGHT<500) {
        zTableView = [[UITableView alloc] initWithFrame:CGRectMake(10,withdrawView.bottom, self.view.frame.size.width-19, SCREEN_HEIGHT-navView.bottom-60-55-60)];
    }else{
        zTableView = [[UITableView alloc] initWithFrame:CGRectMake(10,withdrawView.bottom, self.view.frame.size.width-19, SCREEN_HEIGHT-navView.bottom-60-55)];
    }
    zTableView.delegate = self;
    zTableView.dataSource = self;
    [self.view addSubview:zTableView];
       [self addRefreshView];
    zTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    zTableView.backgroundColor = [UIColor clearColor];
    [zTableView registerClass:[WithdrawLTableViewCell class] forCellReuseIdentifier:@"cell"];
//    zTableView.bounces = NO;
    [self setExtraCellLineHidden:zTableView];
    
}
- (void)addRefreshView {
    
    __weak __typeof(self)weakSelf = self;
    //上拉加载更多
    footerView = [zTableView addFooterWithRefreshHandler:^(FCXRefreshBaseView *refreshView) {
        [weakSelf loadMoreAction];
    }];
    
}
- (void)loadMoreAction {
    pageWithNotDeliver++;
    __weak UITableView *weakTableView =  zTableView;
    __weak FCXRefreshFooterView *weakFooterView = footerView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_data gainWithdrawRecord:[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] andPageID:[NSString stringWithFormat:@"%ld",(long)pageWithNotDeliver] andPerPage:@"15" andStartTime:@"" andEndTime:@""];
        [weakTableView reloadData];
        [weakFooterView endRefresh];
    });
}

#pragma mark -点击日期
- (void)dateBtnAction:(UIButton *)btn
{
    NSLog(@"日期");
    self.pmCC = [[PMCalendarController alloc] init];
    pmCC.delegate = self;
    pmCC.mondayFirstDayOfWeek = YES;
    
    [pmCC presentCalendarFromView:btn
         permittedArrowDirections:PMCalendarArrowDirectionAny
                         animated:YES];
    
    [self calendarController:pmCC didChangePeriod:self.pmCC.period];
    
    
}

static int i = 0;
- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    self.dateBtn.titleLabel.text = [NSString stringWithFormat:@"%@"
                                    , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM"]];
    
    dateNow =[NSString stringWithFormat:@"%@"
              , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-dd"]];
    if (i%2!=0) {
        [self.pmCC dismissCalendarAnimated:YES];
        
        //        AccountHandleData *data = [[AccountHandleData alloc] init];
        //        data.delegate = self;
        //        [data topUPRecords:single.buyerModel.user_id andTime:dateNow];
        NSLog(@"%@",dateNow);
        NSString *str = [dateNow substringWithRange:NSMakeRange(8, 2)];
        
        NSString *startTime =[dateNow stringByReplacingOccurrencesOfString:str withString:@"01"];
        NSString *endTime =[dateNow stringByReplacingOccurrencesOfString:str withString:@"30"];
        YoungAllData *data  = [[YoungAllData alloc]init];
        data.delegate = self;
        [GMDCircleLoader setOnView:self.view withTitle:@"加载中..." animated:YES];

        [data gainWithdrawRecord:[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"] andPageID:@"1" andPerPage:@"15" andStartTime:startTime andEndTime:endTime];
    }
    
    i++;
    
    
}

#pragma mark - 隐藏多余的分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView

{
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [zArrayData count];
    
    /*
    //    if (self.arr.count<t*6) {
    if (1) {
        if (SCREEN_HEIGHT<500) {
            //return self.arr.count-(t-1)*5;
            return [zArrayData count];
        }else{
            //return self.arr.count-(t-1)*6;
            return 30;
        }
    }else{
        if (SCREEN_HEIGHT<500) {
            return 4;
        }else{
            return 6;
        }
    }
     */
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    WithdrawLTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[WithdrawLTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    NSDictionary *dic = [zArrayData objectAtIndex:indexPath.row];
    
    if (dic[@"AddDate"] == nil ||[dic[@"AddDate"] isEqual:[NSNull null]]) {
         cell.zDate.text = @"";
    } else{
        cell.zDate.text = dic[@"AddDate"];
    }
    
    if (dic[@"AddHour"] == nil ||[dic[@"AddHour"] isEqual:[NSNull null]]) {
        cell.zTime.text = @"";
    } else{
        cell.zTime.text = dic[@"AddHour"];
    }
    if (dic[@"WithdrawAmount"] == nil ||[dic[@"WithdrawAmount"] isEqual:[NSNull null]]) {
        cell.zPrice.text = @"";
    } else{
        cell.zPrice.text = dic[@"WithdrawAmount"];
    }
    if (dic[@"WithdrawStatus"] == nil ||[dic[@"WithdrawStatus"] isEqual:[NSNull null]]) {
        cell.zState.text = @"";
    } else{
        cell.zState.text = dic[@"WithdrawStatus"];
    }
    return cell;
    
}

#pragma 返回
-(void)clickBackBtn{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取当前时间
-(void)strtime{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    now=[NSDate date];
    comps = [calendar components:unitFlags fromDate:now];
    NSInteger year = [comps year];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    NSString *monthStr ;
    NSString *dayStr ;
    if (month < 10 || day < 10) {
        if (month <10) {
            monthStr = [NSString stringWithFormat:@"0%ld",(long)month];
        }else{
            monthStr = [NSString stringWithFormat:@"%ld",(long)month];
        }
        if(day < 10){
            dayStr = [NSString stringWithFormat:@"0%ld",(long)day];
        }else{
            dayStr = [NSString stringWithFormat:@"%ld",(long)day];
        }
    }else{
        monthStr = [NSString stringWithFormat:@"%ld",(long)month];
        dayStr = [NSString stringWithFormat:@"%ld",(long)day];
    }
    //dateNow = [NSString stringWithFormat:@"%ld-%@-%@",(long)year,monthStr,dayStr];
    dateNow = [NSString stringWithFormat:@"%ld-%@",(long)year,monthStr];
}

@end
